﻿public class BitMask
{
    private readonly byte[] m_BitMask;
    private readonly int m_BitCount;
    private readonly int m_BlockCount;

    public BitMask(int n)
    {
        m_BitCount = n;
        m_BlockCount = U8_SIZE(n);
        m_BitMask = new byte[m_BlockCount];
    }

    public void Load(NetPacket pck)
    {
        for (int i = 0; i < m_BlockCount; ++i)
        {
            pck.Read(out m_BitMask[i]);
        }
    }

    public int FindFirst()
    {
        for (int i = 0; i < m_BitCount; ++i)
        {
            if (U8_BIT_ISSET(m_BitMask, i))
            {
                return i;
            }
        }
        return -1;
    }

    public int FindNext(int i)
    {
        for (++i; i < m_BitCount; ++i)
        {
            if (U8_BIT_ISSET(m_BitMask, i))
            {
                return i;
            }
        }
        return -1;
    }

    public int Size()
    {
        return m_BitCount;
    }

    private static int U8_SIZE(int n)
    {
        return (n >> 3) + ((n & ((1 << 3) - 1)) != 0 ? 1 : 0);
    }
    private static bool U8_BIT_ISSET(byte[] Array, int i)
    {
        return Utils.BIT_ISSET(Array[i >> 3], i & ((1 << 3) - 1));
    }
}
